<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/23
 * Time: 17:09
 */

namespace App\Game\Traits;


use Carbon\Carbon;

trait KyTrait
{
    public function apiDataParse(array $apiData, array $data)
    {
        $data = $this->usernamePre($data);
        return $data;
    }

    private function usernamePre(array $data)
    {
        if (array_key_exists('username', $data)) {
            $data['username'] = str_after($data['username'], $this->clearPre);
        }
        return $data;
    }

    /**
     * gameapi
     * 2018/9/21 9:43
     * Administrator
     * parseTimeInterval
     * 将时间拆分成最长一小时的时间断
     * @param Carbon $startTime
     * @param Carbon $endTime
     * @return array
     */
    public function parseTimeInterval(Carbon $startTime, Carbon $endTime)
    {
        $timeArray = [];
        $startHour = (clone $startTime)->startOfHour();
        $diffHours = $startHour->diffInHours($endTime, false);
        if ($startTime->diffInHours($endTime, false) >= 1) {
            for ($i = 0; $i <= $diffHours; $i++) {
                if ($i <= $diffHours - 1) {
                    $start = (clone $startTime)->addHour($i)->timestamp;
                    $end = (clone $startTime)->addHour($i + 1)->timestamp;
                } else {
                    $start = (clone $startTime)->addHour($i)->timestamp;
                    $end = (clone $endTime)->timestamp;
                }
                $timeArray[] = compact('start', 'end');
            }
        } else {
            $start = (clone $startTime)->timestamp;
            $end = (clone $endTime)->timestamp;
            $timeArray[] = compact('start', 'end');
        }


        return $timeArray;
    }

    function desEncode($key, $str)
    {
        $str = $this->pkcs5_pad(trim($str), 16);
        $encrypt_str = openssl_encrypt($str, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
        return base64_encode($encrypt_str);
    }

    function pkcs5_pad($text, $blocksize)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
}